package com.qiantu.phone.ui.dialog;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.toast.ToastUtils;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.widget.CalendarView;
import com.lxj.xpopup.core.BottomPopupView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class BottomCalendarSelectDialog extends BottomPopupView implements View.OnClickListener {
    private final int TIME_AREA = 3;//时间跨度为3年
    private final int SELECT_AREA = 30;//选择范围为30天
    int selectMonth;
    int selectYear;
    int curMonth;
    int curYear;
    Date curDate;
    Date intervalStart;
    Date intervalEnd;
    private TextView mYear;
    private RecyclerView mYearList;
    private RecyclerView mMonthList;
    private CalendarView mCalendar;
    private ImageView mClose;
    private TextView mSave;
    private TextView mReset;
    private YearAdapter yearAdapter;
    private MonthAdapter monthAdapter;
    private View mYearListOutside;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    public BottomCalendarSelectDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.bottom_calendar_select_dialog;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        initView();
    }

    private void initView() {
        mYear = findViewById(R.id.year);
        mYearList = findViewById(R.id.year_list);
        mMonthList = findViewById(R.id.month_list);
        mCalendar = findViewById(R.id.calendar);
        mClose = findViewById(R.id.close);
        mSave = findViewById(R.id.save);
        mReset = findViewById(R.id.reset);
        mYearListOutside = findViewById(R.id.year_list_outside);
        curDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(curDate);
        curMonth = calendar.get(Calendar.MONTH) + 1;
        curYear = calendar.get(Calendar.YEAR);
        selectYear = curYear;
        selectMonth = curMonth;

        //设置当前时间
        mCalendar.setDate(curDate);
        //时段选择
        mCalendar.setInterval(true);
        //设置选中区间
        //mCalendar.setIntervalStart(new Date().getTime());
        //mCalendar.setIntervalEnd(new Date().getTime());
        //设置可选区间

        calendar.add(Calendar.YEAR,-TIME_AREA);//3年前
        mCalendar.setMinTime(calendar.getTime().getTime());
        mCalendar.setMaxTime(curDate.getTime());
        //选择监听
        mCalendar.setOnIntervalSelectListener((view, start, end) -> {
            if (start!=null && end!=null){
                if (intervalDayCount(start, end) > SELECT_AREA){
                    mReset.performClick();
                    ToastUtils.show("时间跨度不能超过30天");
                }else {
                    mSave.setEnabled(true);
                    intervalStart = start;
                    intervalEnd = end;
                }
            }else {
                mSave.setEnabled(false);
            }
        });


        mYear.setText(String.valueOf(selectYear));
        mYear.setOnClickListener(this);
        mReset.setOnClickListener(this);
        mSave.setOnClickListener(this);
        mClose.setOnClickListener(this::onClick);
        mYearListOutside.setOnClickListener(this::onClick);

        List<String> yearData = new ArrayList<>();
        for (int i = 0; i <= TIME_AREA; i++) {
            yearData.add(String.valueOf(selectYear-i));
        }
        yearAdapter = new YearAdapter();
        mYearList.setLayoutManager(new LinearLayoutManager(getContext()));
        mYearList.setAdapter(yearAdapter);
        yearAdapter.setNewInstance(yearData);
        yearAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                selectYear = Integer.parseInt(yearAdapter.getData().get(position));
                mYear.setText(String.valueOf(selectYear));
                mCalendar.setYear(selectYear);
                mYearList.setVisibility(GONE);
                mYearListOutside.setVisibility(GONE);
                monthAdapter.notifyDataSetChanged();
            }
        });

        List<String> monthData = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12");
        monthAdapter = new MonthAdapter();
        mMonthList.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false));
        mMonthList.setAdapter(monthAdapter);
        monthAdapter.setNewInstance(monthData);
        monthAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                int select = Integer.parseInt(monthAdapter.getData().get(position));
                if (selectYear == curYear && select>curMonth){
                    return;
                }
                if (selectYear == curYear-TIME_AREA && select<curMonth){
                    return;
                }
                selectMonth = select;
                monthAdapter.notifyDataSetChanged();
                mCalendar.setMonth(selectMonth);
            }
        });

    }

    private long intervalDayCount(Date start, Date end){
        long diff = end.getTime() - start.getTime();
        long seconds = diff / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = (hours / 24) + 1;
        Log.i("ssssss", days+"");
        return days;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.close:
                dismiss();
                break;
            case R.id.save: {
                String startTime = dateFormat.format(intervalStart);
                String endTime = dateFormat.format(intervalEnd);
                onSave(startTime, endTime);
                break;
            }
            case R.id.reset: {
                selectMonth = curMonth;
                selectYear = curYear;
                mCalendar.initCalendar(new Date());
                mSave.setEnabled(false);
                mYear.setText(curYear+"");
                monthAdapter.notifyDataSetChanged();
                break;
            }
            case R.id.year: {
                mYearList.setVisibility(VISIBLE);
                mYearListOutside.setVisibility(VISIBLE);
                break;
            }
            case R.id.year_list_outside:{
                mYearList.setVisibility(GONE);
                mYearListOutside.setVisibility(GONE);
                break;
            }
        }
    }

    @Override
    protected void onDismiss() {
        super.onDismiss();
        mReset.performClick();
    }

    // 设置最大宽度，看需要而定
    @Override
    protected int getMaxWidth() {
        return super.getMaxWidth();
    }

    // 设置最大高度，看需要而定
    @Override
    protected int getMaxHeight() {
        return super.getMaxHeight();
    }

    /**
     * 弹窗的宽度，用来动态设定当前弹窗的宽度，受getMaxWidth()限制
     *
     * @return
     */
    protected int getPopupWidth() {
        return 0;
    }

    /**
     * 弹窗的高度，用来动态设定当前弹窗的高度，受getMaxHeight()限制
     *
     * @return
     */
    protected int getPopupHeight() {
        return 0;
    }

    public void onSave(String start, String end) {}
    public void onSave(Date startDate, Date endDate) {}

    private class YearAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

        public YearAdapter() {
            super(R.layout.year_item);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder holder, String item) {
            holder.setText(R.id.value, item);
        }
    }

    private int selectColor = AppApplication.getInstance().getThemeColor(R.attr.themeColor);
    private int canSelectColor = AppApplication.getInstance().getThemeColor(R.attr.secondaryColor6);
    private int cannotSelectColor = AppApplication.getInstance().getThemeColor(R.attr.secondaryColor10);
    private class MonthAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

        public MonthAdapter() {
            super(R.layout.month_item);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder holder, String item) {
            holder.setText(R.id.value, item);
            if (selectYear == curYear){
                if (Integer.parseInt(item) > curMonth){
                    holder.setTextColor(R.id.value, cannotSelectColor);//不可选
                }else if (Integer.parseInt(item) == selectMonth) {
                    holder.setTextColor(R.id.value, selectColor);//选中
                }else {
                    holder.setTextColor(R.id.value, canSelectColor);//可选
                }
            }else if (selectYear == curYear - TIME_AREA){
                if (Integer.parseInt(item) < curMonth){
                    holder.setTextColor(R.id.value, cannotSelectColor);//不可选
                }else if (Integer.parseInt(item) == selectMonth){
                    holder.setTextColor(R.id.value, selectColor);//选中
                }else {
                    holder.setTextColor(R.id.value, canSelectColor);//可选
                }
            }else {
                holder.setTextColor(R.id.value, selectColor);//选中
            }
        }
    }
}
